<?php
/**
 * CreateTime: 2023/12/5 14:28
 * User:LinQ
 */

namespace App\Http\Controllers\System;

use App\Facade\UserFuncFacade;
use App\Func\File\FileFunc;
use App\Http\Controllers\Controller;
use App\Models\Files\FilesModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class UploadController extends Controller
{
    public function upload(){
        $file = request()->file('file');
        $data = request()->only('extra','utk','u_dept');
        $extra = $data['extra'] ?? "";
        $utk = $data['utk'] ?? "";
        $u_dept = $data['u_dept'] ?? "";
        // 获取文件原始名称
        $originalName = $file->getClientOriginalName();
        // 获取文件临时存储位置
        $path = $file->getRealPath();
        // 获取mimeType
        $mimeType = $file->getMimeType();
        // 获取文件后缀名
        $ext = $file->getClientOriginalExtension();
        // 允许通过的后缀 配置
        $canUploadArr = [
            // 图片
            'jpg',
            'jpeg',
            'png',
            'gif',
            // 压缩文件
            'zip',
            'rar',
            '7z',
            // 文本文件
            'txt',
            'doc',
            'docx',
            'xls',
            'xlsx',
            // 其他文件
            'pdf',
        ];
        $compressData = [
            'jpg',
            'jpeg',
            'png',
            'gif',
        ];
        if(!in_array($ext,$canUploadArr)){
            s_fail_return(null,trans('message.upload_err',[
                'code'=>1001,
                'name' => trans('key.file_format_err')
            ]));
        }

        // mimeType校验
        if(!map_has_value(config('file_mime_type'),$ext)){
            s_fail_return(null,trans('message.upload_err',[
                'code'=>1002,
                'name' => trans('key.file_format_err')
            ]));
        }

        $error = $file->getError();
        if($error){
            s_fail_return(null,trans('message.upload_err',[
                'code'=>1003,
                'name' => ''
            ]));
        }
        $currentUserInfo = UserFuncFacade::getLoginInfo($utk,$u_dept);
        // 生成文件夹
        $dir = "com_id-".$currentUserInfo['com_id'].DIRECTORY_SEPARATOR."dept-".$u_dept."-".date("Ymd");
        // 生成加密后的文件地址
        $pName = md5($originalName.time());
        $encryptionFileUrl = "file".DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR.$pName.".".$ext;
        // 文件保存
        $uploadRes = Storage::disk()->put($encryptionFileUrl,file_get_contents($path));
        if(!$uploadRes){
            s_fail_return(null,trans('message.upload_err',[
                'code'=>1004,
                'name' => ''
            ]));
        }
        DB::beginTransaction();
        try {
            $fileId = (new FileFunc())->insertFileData(
                $currentUserInfo['user_id'],
                $originalName,
                hash_file('sha256',Storage::path($encryptionFileUrl)),
                $encryptionFileUrl
            );
            if(!in_array($ext,$canUploadArr)){
               $compressId =  (new FileFunc())->compressImage(
                    $currentUserInfo['user_id'],
                    $dir,
                    $path,
                    $fileId,
                    $pName,
                    $ext
                );
               if(!$compressId){
                   s_fail_return(null,trans('message.upload_err',[
                       'code'=>1006 ,
                       'name' => ''
                   ]));
               }
            }
            DB::commit();
            s_c_return([
                'file_id' => $fileId,
                'file_name'=>$originalName,
                'file_path'=>$encryptionFileUrl,
                'file_ext'=>$ext
            ],trans('message.upload_ok'));
        }catch (\Exception $exception){
            s_fail_return(null,trans('message.upload_err',[
                'code'=>1005,
                'name' => ''
            ]));
        }
    }

    public function download($fileId){
        $fileInfo = FilesModel::find($fileId);
        if(!$fileInfo){
            s_fail_return(null,trans('message.download_err'));
        }
        return Storage::download($fileInfo['file_path'], $fileInfo['file_name']);
    }
}
